﻿using FlyingEye.ComServices;
using FlyingEye.HttpServices;
using System.Text.Json;
using Volo.Abp.DependencyInjection;

namespace FlyingEye.ComeServices
{
    /// <summary>
    /// COME 通知服务
    /// </summary>
    public class ComeNotificationService : ITransientDependency
    {
        private readonly ILogger<ComeNotificationService> _logger;

        private readonly IHttpClientFactory _httpClientFactory;

        public ComeNotificationService(IHttpClientFactory httpClientFactory,
            ILogger<ComeNotificationService> logger)
        {
            _httpClientFactory = httpClientFactory;
            _logger = logger;
        }

        /// <summary>
        /// 构建请求消息
        /// </summary>
        private static HttpRequestMessage BuildRequestMessage(
           HttpMethod method,
           string url,
           object? content,
           string authKey)
        {
            var request = new HttpRequestMessage(method, url);

            request.Headers.Add("deipaaskeyauth", authKey);

            if (content != null)
            {
                request.Content = JsonContent.Create(content, options: new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                });
            }

            return request;
        }

        /// <summary>
        /// 处理相应消息
        /// </summary>
        private static async Task<TResult> HandleResponse<TResult>(HttpResponseMessage response)
        {
            if (!response.IsSuccessStatusCode)
            {
                var errorContent = await response.Content.ReadAsStringAsync();
                throw new HttpClientServiceException($"HTTP 错误: {response.StatusCode}\n{errorContent}");
            }

            try
            {
                return await response.Content.ReadFromJsonAsync<TResult>()
                    ?? throw new InvalidDataException("响应内容为空");
            }
            catch (JsonException ex)
            {
                throw new HttpClientDataFormatException("JSON 反序列化失败", ex);
            }
        }

        const string Url = "https://ipaas.catl.com/gateway/office/ipaas/MSG/office_MSG_push";

        /// <summary>
        /// 向指定群组发送通知
        /// </summary>
        public async Task<DefaultActionResult> NotifyAsync(ComeUserNotificationConfiguration configuration, ComeUserNotification notification)
        {
            using var httpClient = _httpClientFactory.CreateClient("ComeUserNotification");

            var body = new ComNotificationConfiguration(
                agentId: configuration.AgentId,
                templateData: new NotificationTemplate(
                    AccessToken: string.Empty,
                    Secret: string.Empty,
                    Text: notification.Message,
                    Title: notification.Title),
                isAt: false,
                templateId: configuration.TemplateId,
                toAll: false,
                users: notification.UserIds,
                "ding");

            var request = BuildRequestMessage(HttpMethod.Post, Url, body, configuration.AuthKey);

            try
            {
                var response = await httpClient.SendAsync(request);

                var result = await HandleResponse<ComeNotificationResponse>(response);

                if (result.Code == 0)
                {
                    return DefaultActionResult.GetSuccessResult("用户通知完成。");
                }
                else
                {
                    return DefaultActionResult.GetFailureResult($"用户通知失败，code={result.Code}.");
                }
            }
            catch (Exception ex)
            {
                var error = $"[{Guid.NewGuid()}]COME 用户信息通知失败。";
                _logger.LogError(ex, error);
                return DefaultActionResult.GetFailureResult(error);
            }
        }

        /// <summary>
        /// 向指定用户发送通知
        /// </summary>
        public async Task<DefaultActionResult> NotifyAsync(ComeGroupNotificationConfiguration configuration, ComeGroupNotification notification)
        {
            using var httpClient = _httpClientFactory.CreateClient("ComeGroupNotification");

            var body = new ComNotificationConfiguration(
                agentId: configuration.AgentId,
                templateData: new NotificationTemplate(
                    AccessToken: configuration.AccessToken,
                    Secret: configuration.Secret,
                    Text: notification.Message,
                    Title: notification.Title),
                isAt: false,
                templateId: configuration.TemplateId,
                toAll: false,
                users: new List<string>() { "60218718" },
                "ding");

            var request = BuildRequestMessage(HttpMethod.Post, Url, body, configuration.AuthKey);

            try
            {
                var response = await httpClient.SendAsync(request);

                var result = await HandleResponse<ComeNotificationResponse>(response);

                if (result.Code == 0)
                {
                    return DefaultActionResult.GetSuccessResult("群组通知完成。");
                }
                else
                {
                    return DefaultActionResult.GetFailureResult($"群组通知失败，code={result.Code}.");
                }
            }
            catch (Exception ex)
            {
                var error = $"[{Guid.NewGuid()}]COME 群组信息通知失败。";
                _logger.LogError(ex, error);
                return DefaultActionResult.GetFailureResult(error);
            }
        }
    }
}
